package com.atguigu.demo02;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author gjl
 * @create 2021-04-24 9:24
 */
public class Demo {

    private int number = 0;

    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();


    /*public synchronized void increment() throws InterruptedException {
        //判断
        if(number != 0){
            this.wait();
        }
        //干活
        number++;
        System.out.println(Thread.currentThread().getName()+" "+number);
        //通知
        this.notify();
    }*/

    /*public synchronized void de() throws InterruptedException {
        //判断
        if (number == 0) {
            this.wait();
        }
        //干活
        number--;
        System.out.println(Thread.currentThread().getName() + " " + number);
        //通知
        this.notify();
    }*/

    public  void increment() throws InterruptedException {

        lock.lock();
        try {

            //判断
            while (number != 0) {
                condition.await();
            }

            //干活
            number++;
            System.out.println(Thread.currentThread().getName() + " " + number);

            //通知
            condition.signal();
        } finally {
            lock.unlock();

        }
    }
    public  void de() throws InterruptedException {
        lock.lock();
        try {
            //判断
            while (number == 0) {
                condition.await();
            }
            //干活
            number--;
            System.out.println(Thread.currentThread().getName() + " " + number);
            //通知
            condition.signal();
        } finally {
            lock.unlock();
        }
    }


}
